package com.zxcz.security;

import java.util.Collection;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import com.zxcz.tools.Constants;

/**
 * 用户登录认证
 * @author root
 *
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter{
		
		/**
		 * 认证策略
		 */
		@Override
		protected void configure(HttpSecurity http) throws Exception {
			http.authorizeRequests()
			.antMatchers("/css/**","/js/**","/storage/**","/bower_components/**","/dist/**").permitAll()
			.antMatchers("/**")
			.fullyAuthenticated()
			.and()
			.formLogin()
			.loginPage("/login").permitAll() //放行登录
			.successHandler((req, res, authentication)->{
				//获取用户的角色
				User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
				Collection<GrantedAuthority> authorities = principal.getAuthorities();
				GrantedAuthority grantedAuthority = null;
				if(authorities.iterator().hasNext()) {
					grantedAuthority = authorities.iterator().next();
				}
				
				//管理员角色
				SimpleGrantedAuthority status = new SimpleGrantedAuthority(Constants.ROLE_ADMIN_NAME);
				//判断用户是否是管理员跳转相应界面
				if(grantedAuthority.equals(status)) {
					res.sendRedirect("/firmwareManage");
				}else {
					res.sendRedirect("/userResourceManage");
				}
			})
			.failureForwardUrl("/login")
			.and()
			.logout()
			.logoutRequestMatcher(new AntPathRequestMatcher("/logout","POST"))// 用户退出所访问的路径，需要使用Post方式
			.logoutSuccessUrl("/login")
			.invalidateHttpSession(true)
			.and()
			.headers().frameOptions().disable(); //允许iframe
			
		}
		
	
	
	
}
